package com.github.defense.sync.data.nacos;

import com.alibaba.nacos.api.config.ConfigService;
import com.github.defense.common.constant.DefaultConstants;
import com.github.defense.common.exception.DefenseException;
import com.github.defense.sync.data.api.PluginSubscriber;
import com.github.defense.sync.data.nacos.handler.NacosCacheHandler;

import java.util.Objects;

/**
 * 主要用来同步网关配置数据
 * 启动项目的时候启动一个监听器 通过Nacos的变更数据监听来实现
 *
 * @Author: lettger
 * @Date: 2021/12/6 上午10:20
 */
public class NacosSyncDataService extends NacosCacheHandler implements AutoCloseable {


    public NacosSyncDataService(ConfigService configService, PluginSubscriber subscriber) {
        super(configService,subscriber);
        start();
    }

    /**
     * 启动监听
     */
    private void start() {
        watch(DefaultConstants.NACOS_PLUGIN_DATA_ID, this::syncPlugin);
        watch(DefaultConstants.NACOS_GATEWAY_DATA_ID, this::syncGateway);
        watch(DefaultConstants.NACOS_APP_DATA_ID, this::syncAppInfo);
    }

    /**
     * 移除Nacos监听
     */
    @Override
    public void close() throws Exception {
        LISTENERS.forEach((dataId, ls) -> {
            ls.forEach(listener -> getConfigService().removeListener(dataId, DefaultConstants.NACOS_DEFAULT_GROUP, listener));
            ls.clear();
        });
        LISTENERS.clear();
    }
}
